package com.ruoyi.crm.modules.email;

import com.ruoyi.crm.domain.Contract;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

@Service
public class CrmMailService {
    private static final String TEMPLATE_CONTRACT_CREATED = "contractCreated.html";
    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String username;

    @SneakyThrows
    public void sendContractCreatedMail(Contract contract) {
        Context context = new Context();
        context.setVariable("userName", contract.getName());
        context.setVariable("contractNo", contract.getContractNo());
        context.setVariable("contractOrder", contract.getContractOrder());
        String mailText = templateEngine.process(TEMPLATE_CONTRACT_CREATED, context);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setSubject("感谢您成功订购：【" + contract.getCourseName() + "】");
        helper.setFrom(username);
        helper.setTo(contract.getEmail());
        helper.setText(mailText, true);
        javaMailSender.send(mimeMessage);
    }
}
